import modelEnhance from '@/utils/modelEnhance';
import PageHelper from '@/utils/pageHelper';

import config from '../../../config.js';

const noticeGlobal = config.notice;

/**
 * 当第一次加载完页面时为true
 * 可以用这个值阻止切换页面时
 * 多次初始化数据
 */
let LOADED = false;
export default modelEnhance({
  namespace: 'classes',

  state: {
    pageData: PageHelper.create(),
    classes: [],
    lecturers: [],
    students: [],
    lessons: [],
    classInfo: new Object(),
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname }) => {
        if (pathname === '/classes' && !LOADED) {
          // LOADED = true;
          dispatch({
            type: 'init'
          });
        }
      });
    }
  },

  effects: {
    // 进入页面加载
    *init({ payload }, { call, put, select }) {
      const { pageData } = yield select(state => state.classes);
      yield put({
        type: 'getPageInfo',
        payload: {
          pageData: pageData.startPage(1, 10)
        }
      });
      yield put.resolve({
        type: '@request',
        afterResponse: resp => resp.data.records.map(item=> {return {'key': item.id, 'title': item.realname}}),
        payload: {
          url: '/api/teacher/allList',
          valueField: 'lecturers',
          data: {},
        }
      });
      yield put.resolve({
        type: '@request',
        afterResponse: resp => resp.data.records.map(item=> {return {'key': item.id, 'title': item.realname}}),
        payload: {
          url: '/api/student/list',
          data: {},
          valueField: 'students',
        }
      });
      yield put.resolve({
        type: '@request',
        afterResponse: resp => resp.data.records.map(item=> {return {'key': item.id, 'title': item.name}}),
        payload: {
          url: '/api/lesson/lessonInfoAllList',
          data: {},
          valueField: 'lessons',
        }
      });

    },
    // 获取分页数据
    *getPageInfo({ payload }, { call, put }) {
      const {pageData} = payload;
      yield put.resolve({
        type: '@request',
        afterResponse: resp=> pageData.setPage(resp),
        payload: {
          valueField: 'pageData',
          url: '/api/class/getByPage',
          data: pageData.pageinfoData(),
        }
      })
    },
    // 保存 之后查询分页
    *save({ payload }, { call, put, select, take }) {
      const { values, success } = payload;
      const { pageData } = yield select(state => state.classes);
      // put是非阻塞的 put.resolve是阻塞型的
      yield put.resolve({
        type: '@request',
        payload: {
          notice: true,
          url: '/api/class/addList',
          data: [values]
        },
      });

      yield put({
        type: 'getPageInfo',
        payload: { pageData }
      });
      success();
    },
    // 修改
    *update({ payload }, { call, put, select }) {
      const { values, success } = payload;
      const {pageData} = yield select(state => state.classes);

      yield put.resolve({
        type: '@request',
        payload: {
          notice: true,
          url: '/api/class/modify',
          data: values
        }
      });
      yield put({
        type: 'getPageInfo',
        payload: { pageData }
      });
      success();
    },
    // 删除 之后查询分页
    *remove({ payload }, { call, put, select }) {
      const { records, success } = payload;
      const { pageData } = yield select(state => state.classes);
      yield put({
        type: '@request',
        payload: {
          method: 'DELETE',
          notice: true,
          url: '/api/class/delete',
          data: records.map(item => item.id)
        }
      });
      yield put({
        type: 'getPageInfo',
        payload: { pageData }
      });
      success();
    },

    *getClassInfo({payload}, {call, put, select}){
      const {classId, success} = payload;
      const { classInfo } = yield select(state => state.classes);
      let unique_arr =  arr => arr.filter((elem, index, self) => {
        return index == self.indexOf(elem)
      });

      yield put.resolve({
        type: '@request',
        afterResponse: resp=> {
          classInfo.students = resp.data.studentIds;
          classInfo.lecturers = resp.data.teacherIds;
          classInfo.lessons = unique_arr(resp.data.lessonIds);
          return classInfo;
          },
        payload: {
          method: 'GET',
          valueField: 'classInfo',
          url: '/api/class/getById/' + classId,
        }
      });
      success();
    },

    // 人员管理
    *manageClass({payload}, {call, put, select, all}){
      const {values, record, success} = payload;
      const { classInfo } = yield select(state => state.classes);

      const {lecturers, students, lessons} = values;
      const minus_lecturers = classInfo.lecturers.filter(v=> {return lecturers.indexOf(v) == -1});
      const plus_lecturers = lecturers.filter(v=> {return classInfo.lecturers.indexOf(v) == -1});
      const minus_students = classInfo.students.filter(v=> {return students.indexOf(v) == -1});
      const plus_students = students.filter(v=> {return classInfo.students.indexOf(v) == -1});
      const minus_lessons = classInfo.lessons.filter(v=> {return lessons.indexOf(v) == -1});
      const plus_lessons = lessons.filter(v=> {return classInfo.lessons.indexOf(v) == -1});

      if(plus_students && plus_students.length > 0){
      yield put.resolve({
        type: '@request',
        payload: {
          url:'/api/class/assignStudents',
          data: {classId: record.id, userIds: students}
        }
      });}
      if(minus_students && minus_students.length > 0){
      yield put.resolve({
        type: '@request',
        payload: {
          url:'/api/class/unassignStudents',
          data: {classId: record.id, userIds: minus_students}
        }
      });}
      if(plus_lecturers && plus_lecturers.length > 0){
        yield put.resolve({
        type: '@request',
        payload: {
          url:'/api/class/assignTeachers',
          data: {classId: record.id, userIds: lecturers}
        }
      });}

      if(minus_lecturers && minus_lecturers.length > 0){
        yield put.resolve({
          type: '@request',
          payload: {
            url:'/api/class/unassignTeachers',
            data: {classId: record.id, userIds: minus_lecturers}
          }
        });}

      yield all(plus_lessons.map(item => put.resolve({
        type: '@request',
        payload: {
          url:'/api/class/classAddLesson',
          data: {id: record.id, lessonInfoId: item}
        }
      })));

      yield all(minus_lessons.map(item => put.resolve({
        type: '@request',
        payload: {
          method: 'DELETE',
          url:'/api/class/classRemoveLesson',
          data: {id: record.id, lessonInfoId: item}
        }
      })));

      success()
    }
  },

  reducers: {}

});
